#ifndef __CLIENTARRAYRENDERER_H__
#define __CLIENTARRAYRENDERER_H__

#include "RendererBase.h"
#include "Mesh.h"
#include <GL/glew.h>
#include <GL/GL.h>

class ClientArrayRenderer : public RendererBase
{
	bool _compiled;

public:
	ClientArrayRenderer() :
	  _compiled(glewGetExtension("GL_EXT_compiled_vertex_array") != GL_FALSE)
	{
	}

	void RenderMesh(const Mesh &mesh)
	{
		BindTexture(mesh.Texture);

		glPushMatrix();

		glTranslatef(mesh.Pivot.X, mesh.Pivot.Y, mesh.Pivot.Z);
		glRotatef(mesh.Rotate.X, 1, 0, 0);
		glRotatef(mesh.Rotate.Y, 0, 1, 0);
		glRotatef(mesh.Rotate.Z, 0, 0, 1);
		glTranslatef(-mesh.Pivot.X, -mesh.Pivot.Y, -mesh.Pivot.Z);

		glTranslatef(mesh.Translate.X, mesh.Translate.Y, mesh.Translate.Z);

		for (std::vector<Face>::const_iterator face = mesh.Faces.begin(); face != mesh.Faces.end(); ++face)
		{
			glVertexPointer(3, GL_FLOAT, 0, (*face).Vertices.data());
			glTexCoordPointer(2, GL_FLOAT, 0, (*face).TexCoords.data());
			glColorPointer(4, GL_UNSIGNED_BYTE, 0, (*face).Colors.data());

			if (_compiled)
				glLockArraysEXT(0, (*face).Indices.size());
			glDrawElements(mesh.Mode, (*face).Indices.size(), GL_UNSIGNED_INT, (*face).Indices.data());
			if (_compiled)
				glUnlockArraysEXT();
		}

		glPopMatrix();
	}

protected:
	void PreRender()
	{
		glEnableClientState(GL_VERTEX_ARRAY);
		glEnableClientState(GL_COLOR_ARRAY);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	}

	void PostRender()
	{
		glDisableClientState(GL_VERTEX_ARRAY);
		glDisableClientState(GL_COLOR_ARRAY);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	}
};

#endif